import React, {PureComponent} from "react";
import {Button, Divider, Form, Icon, Input, InputNumber, notification, Popconfirm, Select, Table} from "antd";
import {tableProps} from "../../lib/ui";
import {
    calculateFee,
    getById,
    reCalculateFeeById,
    showCreateOrderFee,
    showUpdateOrderFee,
    updateBaoGuanFeeCount,
    updateFeeList,
    updateOrderFee
} from "./actions";
import {connect} from "react-redux";
import {getPrincipal} from "../../lib/identity";
import {formatDate} from "../../lib/func";

const {Option} = Select;
const EditableContext = React.createContext();

const EditableRow = ({form, index, ...props}) => (
    <EditableContext.Provider value={form}>
        <tr {...props} />
    </EditableContext.Provider>
);

const EditableFormRow = Form.create()(EditableRow);

class EditableCell extends React.Component {
    state = {
        editing: false,
    };

    toggleEdit = () => {
        const editing = !this.state.editing;
        this.setState({editing}, () => {
            if (editing) {
                this.input.focus();
            }
        });
    };

    save = e => {
        const {record, handleSave} = this.props;
        this.form.validateFields((error, values) => {
            if (error && error[e.currentTarget.id]) {
                return;
            }
            this.toggleEdit();
            handleSave({...record, ...values});
        });
    };

    saveCurrency = e => {
        const {record, handleSave} = this.props;
        this.form.validateFields((error, values) => {
            if (error && error[e]) {
                return;
            }
            this.toggleEdit();
            values.currency = e;
            handleSave({...record, ...values});
        });
    };

    saveFeeName = e => {
        const {record, handleSave} = this.props;
        this.form.validateFields((error, values) => {
            if (error && error[e]) {
                return;
            }
            this.toggleEdit();
            values.feeName = e;
            const update = {...record, ...values};
            handleSave(update);
        });
    };

    renderCell = form => {
        this.form = form;
        const {children, dataIndex, record, inputType, options = [], placeholder, valueField = "value", labelField = "label"} = this.props;
        const {editing} = this.state;
        let column;
        if (inputType === "number") {
            column = <InputNumber ref={node => (this.input = node)} onPressEnter={this.save} onBlur={this.save}/>;
        } else if (inputType === "select") {
            column = <Select placeholder={placeholder} ref={node => (this.input = node)} style={{width: '100%'}}
                             onChange={this.saveCurrency} allowClear={true}>
                {options.map((item, index) => (
                    <Option key={index} value={item.name}>
                        {item.name}
                    </Option>
                ))}
            </Select>;
        } else if (inputType === 'selectFee') {
            column = <Select placeholder={placeholder} ref={node => (this.input = node)} style={{width: '100%'}}
                             onChange={this.saveFeeName} allowClear={true}>
                {options.map((item, index) => (
                    <Option key={index} value={item[valueField]}>
                        {item[labelField]}
                    </Option>
                ))}
            </Select>;
        } else {
            column = <Input ref={node => (this.input = node)} onPressEnter={this.save} onBlur={this.save}
                            style={{width: '100%'}}/>;
        }
        return editing ? (
            <Form.Item style={{margin: 0}}>
                {form.getFieldDecorator(dataIndex, {
                    initialValue: record[dataIndex],
                })(column)}
            </Form.Item>
        ) : (
            <div
                className="editable-cell-value-wrap"
                style={{paddingRight: 24}}
                onClick={this.toggleEdit}
            >
                {children}
            </div>
        );
    };

    render() {
        const {
            editable,
            dataIndex,
            title,
            record,
            index,
            inputType,
            options,
            placeholder,
            handleSave,
            children,
            valueField,
            labelField,
            ...restProps
        } = this.props;
        return (
            <td {...restProps}>
                {editable ? (
                    <EditableContext.Consumer>{this.renderCell}</EditableContext.Consumer>
                ) : (
                    children
                )}
            </td>
        );
    }
}

class OrderFeeModal extends PureComponent {

    handleShowCreate = () => {
        const {dispatch} = this.props;
        dispatch(showCreateOrderFee());
    };
    handleUpdate = record => {
        const {dispatch} = this.props;
        dispatch(showUpdateOrderFee(record));
    };

    handleSave = values => {
        if (values.status === "LOCK") {
            notification.error({
                message: '费用已锁定,不能修改'
            });
            return;
        }
        const {dispatch, feeList, currencyList} = this.props;
        const found = feeList.find(fee => fee.id === values.id);
        const exist = feeList.find(fee => fee.id !== values.id && fee.feeName === values.feeName);
        if (exist) {
            notification.error({
                message: '存在相同科目的费用,不能添加'
            });
            dispatch(updateFeeList(feeList));
            return;
        }
        if (found) {
            found.feeName = values.feeName;
            found.feeCount = values.feeCount;
            if (values.currency !== undefined && values.currency !== null && values.currency.length > 0) {
                found.currency = values.currency;
            } else {
                // 默认第一个币种
                found.currency = null;
            }
        } else {
            feeList.push(values);
        }
        dispatch(updateFeeList(feeList));

    };

    handleAddFeeName = () => {
        const {dispatch, feeList} = this.props;
        feeList.push({
            "id": Math.random().toString(),
            "feeName": "",
            "feeCount": 0,
            "currency": undefined
        });
        dispatch(updateFeeList(feeList));
    };

    handleAllJiaMi = () => {
        const {dispatch, feeList} = this.props;
        feeList.forEach(item => {
            item.canSee = false;
        });
        dispatch(updateFeeList(feeList));
        notification.success({
            message: '加密成功，保存后生效!'
        });
    };

    handleAllJieMi = () => {
        const {dispatch, feeList} = this.props;
        feeList.forEach(item => {
            item.canSee = true;
        });
        dispatch(updateFeeList(feeList));
        notification.success({
            message: '解密成功，保存后生效!'
        });
    };

    handleJiaMi = record => {
        const {dispatch, feeList} = this.props;
        const found = feeList.find(fee => fee.id === record.id);
        if (found) {
            found.canSee = false;
        }
        dispatch(updateFeeList(feeList));
        notification.success({
            message: '加密成功，保存后生效!'
        });
    };

    handleJieMi = record => {
        const {dispatch, feeList} = this.props;
        const found = feeList.find(fee => fee.id === record.id);
        if (found) {
            found.canSee = true;
        }
        dispatch(updateFeeList(feeList));
        notification.success({
            message: '解密成功，保存后生效!'
        });
    };

    handleDeleteFee = record => {
        const {dispatch, feeList} = this.props;
        const deleteIndex = feeList.findIndex(item => item.id === record.id);
        feeList.splice(deleteIndex, 1);
        dispatch(updateFeeList(feeList));
    };

    handleRefreshFee = record => {
        const {order, dispatch, calculateType} = this.props;
        // 转换计费方式
        let calculateTypeStr = order.calculateType;
        for (let i = 0; i < calculateType.length; i++) {
            if (calculateType[i]['label'] === order.calculateType) {
                calculateTypeStr = calculateType[i]['value'];
                break
            }
        }
        dispatch(calculateFee({
            ...order,
            ...record,
            type: 1,
            calculateTime: formatDate(order.preDepartureTime),
            calculateType: calculateTypeStr
        }));
    };

    onChangeHomeCount = value => {
        const {dispatch, sheetCount, feeList, homeFee = 0, sheetFee = 0, currency} = this.props;
        dispatch(updateBaoGuanFeeCount({homeCount: value, sheetCount}));
        const found = feeList.find(item => item.feeName === "报关费");
        if (found) {
            found.feeCount = (homeFee * value || 0).toFixed(2);
            found.currency = currency;
            dispatch(updateFeeList(feeList));
        } else {
            if ((homeFee * value || 0) > 0) {
                feeList.push({
                    feeName: "报关费",
                    feeCount: (homeFee * value || 0).toFixed(2),
                    currency: currency,
                    canSee: true
                });
                dispatch(updateFeeList(feeList));
            }
        }
    };

    onChangeSheetCount = value => {
        const {dispatch, homeCount, feeList, homeFee = 0, sheetFee = 0, sheetCurrency} = this.props;
        dispatch(updateBaoGuanFeeCount({sheetCount: value, homeCount}));
        const found = feeList.find(item => item.feeName === "报关联单费");
        if (found) {
            found.feeCount = (sheetFee * value || 0).toFixed(2);
            found.currency = sheetCurrency;
            dispatch(updateFeeList(feeList));
        } else {
            if ((sheetFee * value || 0) > 0) {
                feeList.push({
                    feeName: "报关联单费",
                    feeCount: (sheetFee * value || 0).toFixed(2),
                    currency: sheetCurrency,
                    canSee: true
                });
                dispatch(updateFeeList(feeList));
            }
        }
    };

    render() {
        const {loading, feeList = [], feeItemList, order, currencyList, homeFee, sheetFee, currency, sheetCurrency, homeCount, sheetCount, overFee, overFeeCurrency} = this.props;
        const columns = [
            {
                title: "费用科目",
                dataIndex: "feeName",
                editable: true,
                inputType: "selectFee",
                options: feeItemList,
                valueField: "feeName",
                labelField: "feeName",
                placeholder: "请选择费用科目",
                width: "150px",
            }, {
                title: "金额",
                dataIndex: "feeCount",
                editable: true,
                inputType: "number",
                width: "150px",
                render: (text, record) => {
                    if (record.feeName === "运输费") {
                        if (getPrincipal().admin) {
                            return <span>{text}</span>
                        } else {
                            return <span>******</span>
                        }
                    } else {
                        return <span>{text}</span>
                    }
                }
            }, {
                title: "币种",
                dataIndex: "currency",
                editable: true,
                inputType: "select",
                options: currencyList,
                placeholder: "请选择币种",
                width: "150px",
                render: (text, record) => {
                    if (record.feeName === "运输费") {
                        if (getPrincipal().admin) {
                            return <span>{text}</span>
                        } else {
                            return <span>******</span>
                        }
                    } else {
                        return <span>{text}</span>
                    }
                }
            }, {
                title: '功能',
                dataIndex: '',
                key: 'x',
                width: "150px",
                render: (text, record) => {
                    if (order.status === 'CONFIRMED') {
                        return '';
                    }
                    if (record.feeName === "运输费") {
                        if (getPrincipal().admin) {
                            return <span>{record.status !== "LOCK" ?
                                <span>
                                        <Popconfirm title="是否删除费用?" okText="是" cancelText="否"
                                                    onConfirm={() => this.handleDeleteFee(record)}>
                                            <a>删除</a>
                                        </Popconfirm>
                                        <Divider type="vertical"/><a
                                    onClick={() => this.handleRefreshFee(record)}>刷新</a>
                                    </span> : <span>费用已锁定</span>}
                                    </span>
                        } else {
                            return <span/>;
                        }
                    } else {
                        return <span>{record.status !== "LOCK" ?
                            <span>
                                        <Popconfirm title="是否删除费用?" okText="是" cancelText="否"
                                                    onConfirm={() => this.handleDeleteFee(record)}>
                                            <a>删除</a>
                                        </Popconfirm>
                                        <Divider type="vertical"/><a
                                onClick={() => this.handleRefreshFee(record)}>刷新</a>
                                    </span> : <span>费用已锁定</span>}
                                </span>
                    }
                }
            }, {
                title: "",
                dataIndex: ""
            }
        ];

        const found = feeList.find(item => item.feeName === "报关费");
        if (found) {
            found.feeCount = (homeFee * homeCount || 0).toFixed(2);
            found.currency = currency;
        } else if (homeCount > 0 && (homeFee * homeCount || 0) > 0) {
            feeList.push({
                id: Math.random().toString(),
                feeName: "报关费",
                canSee: true,
                feeCount: (homeFee * homeCount || 0).toFixed(2),
                currency: currency
            });
        }
        const found2 = feeList.find(item => item.feeName === "报关联单费");
        if (found2) {
            found2.feeCount = (sheetCount * sheetFee || 0).toFixed(2);
            found2.currency = sheetCurrency;
        } else if (sheetCount > 0 && (sheetCount * sheetFee || 0) > 0) {
            feeList.push({
                id: Math.random().toString(),
                feeName: "报关联单费",
                canSee: true,
                feeCount: (sheetCount * sheetFee || 0).toFixed(2),
                currency: sheetCurrency
            });
        }
        const components = {
            body: {
                row: EditableFormRow,
                cell: EditableCell,
            },
        };
        const editColumns = columns.map(col => {
            if (!col.editable) {
                return col;
            }
            return {
                ...col,
                onCell: record => {
                    let dataIndex = col.dataIndex;
                    let can_edit = true;
                    if (record.feeName === "运输费" && getPrincipal().admin === false) {
                        can_edit = false;
                    }
                    return ({
                        record,
                        editable: can_edit,
                        dataIndex: dataIndex,
                        title: col.title,
                        options: col.options,
                        placeholder: col.placeholder,
                        inputType: col.inputType,
                        valueField: col.valueField,
                        labelField: col.labelField,
                        handleSave: this.handleSave,
                    })
                },
            };
        });
        return (
            <div>
                <div className="actions2">
                    主页费单价：{homeFee}{currency} 主页数：<InputNumber min={0} value={homeCount}
                                                               disabled={order.status === 'CONFIRMED'}
                                                               onChange={this.onChangeHomeCount}/>
                    续页费单价：{sheetFee}{sheetCurrency} 续页数：<InputNumber min={0} value={sheetCount}
                                                                     disabled={order.status === 'CONFIRMED'}
                                                                     onChange={this.onChangeSheetCount}/>
                </div>
                <div className="actions">
                    <Button onClick={this.handleAddFeeName} disabled={order.status === 'CONFIRMED'}><Icon
                        type="add"/>加一行费用</Button>
                </div>
                <h3 style={{color: 'red'}}>计费规则：根据订单客户相同业务类型、计费方式、起始站、目的站、费用科目，并且在有效期范围内才符合计费规则</h3>
                <h3 style={{color: 'red'}}>(注意：国际版列按照班列日期)</h3>
                <Table
                    {...tableProps}
                    tableLayout={'fixed'}
                    columns={order.status === 'CONFIRMED' ? columns : editColumns}
                    dataSource={feeList}
                    components={components}
                    loading={loading}
                    rowClassName={() => 'editable-row'}
                />
            </div>
        );
    }
}

const mapStateToProps = state => {
    return {
        ...state.zadOrder.orderFee,
        order: state.zadOrder.modify.model,
        calculateType: state.common.calculateType,
        currencyList: state.zadOrder.list.currencyList,
        feeItemList: state.zadOrder.orderFee.feeList
    };
};

export default connect(mapStateToProps)(OrderFeeModal);
